import useUserStore from '@/store/user'
import { jump, toast } from '@/common/util'
import { config } from '@/common/config'
import type {
  IRequestOptions,
  TRequestData,
  TRequestMethods,
  IRequestHeader,
  AnyObject
} from '@/common/types'
const { api } = config

interface IRequestConfig {
  api: string;
  method: TRequestMethods;
  header: IRequestHeader;
  data: TRequestData;
  dataType: string;
  [propsName: string]: any;
}

const requestConfig: IRequestConfig = {
  api,
  header: {
    'Content-Type': 'application/json;charset=UTF-8'
    // 'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: {},
  method: 'GET',
  dataType: ''
}

export default {
  // 配置请求参数
  config: requestConfig,
  // 获取网络类型
  getNetwork() {
    return new Promise((resolve): void => {
      uni.getNetworkType({
        complete: (res) => {
          resolve(res.networkType)
        }
      })
    })
  },
  async request(options: IRequestOptions):Promise<any> {
    options.method = options.method || this.config.method
    options.dataType = options.dataType || this.config.dataType
    options.url = this.config.api + options.url
    options.header = options.header || this.config.header
    const network = await this.getNetwork()
    if (!network || network === 'none') {
      toast('网络异常，请检查网络连接')
      return Promise.reject({
        code: 500
      })
    } else {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async(resolve, reject) => {
        const res = await uni.request(options)
        res.data = res.data && JSON.parse(res.data as string)
        if (this.errorCheck(res)) resolve(res.data)
        else reject(res.data)
      })
    }
  },
  async get(
    url: string,
    data?: TRequestData,
    options: IRequestOptions = { url: '' }
  ) {
    options.url = url
    options.data = data
    options.method = 'GET'
    return this.request(options)
  },
  async post(
    url: string,
    data?: TRequestData,
    options: IRequestOptions = {} as IRequestOptions
  ) {
    options.url = url
    options.data = data
    options.method = 'POST'
    return this.request(options)
  },
  async del(
    url: string,
    data?: TRequestData,
    options: IRequestOptions = {} as IRequestOptions
  ) {
    options.url = url
    options.data = data
    options.method = 'DELETE'
    return this.request(options)
  },
  async put(
    url: string,
    data?: TRequestData,
    options: IRequestOptions = {} as IRequestOptions
  ) {
    options.url = url
    options.data = data
    options.method = 'PUT'
    return this.request(options)
  },
  // 错误处理
  errorCheck(res: AnyObject): boolean {
    if (res.statusCode !== 200) {
      toast('网络错误，加载失败')
      return false
    }
    const { data } = res
    if (data.code === 500) {
      toast(data.msg)
      uni.stopPullDownRefresh()
      return false
    }
    return true
  }
}
